package com.asen.commons.core.jdbc.builder.mysql;

import com.asen.commons.core.jdbc.builder.SqlBuilder;
import com.asen.commons.core.jdbc.param.ParamStatementSetter;
import com.asen.commons.core.jdbc.param.SqlContext;
import com.asen.commons.core.jdbc.param.SqlContextManager;
import com.asen.commons.core.meta.entity.FieldObject;
import com.asen.commons.utils.BaseAssert;

/**
 * 新增数据SQL构建器
 *
 * @author Gary
 * @version 1.0
 * @date 2018-11-28
 */
public class InsertBuilder implements SqlBuilder {

    private SqlContext context;

    private boolean buildFlag = false;

    public InsertBuilder(Class<?> modelType) {
        this.context = new SqlContext(modelType);
    }

    @Override
    public String getSql() {
        BaseAssert.check(buildFlag, "尚未进行SQL构建，不能执行此操作！");
        BaseAssert.check(context.hasChangeColumns(), "参数不合法！没有可新增的列");

        StringBuilder columns = new StringBuilder();
        StringBuilder values = new StringBuilder();

        for (String column : context.getColumnList()) {
            if (columns.length() > 0) {
                columns.append(", ");
                values.append(", ");
            }
            columns.append("`").append(column).append("`");
            values.append("?");
        }

        StringBuilder sb = new StringBuilder("INSERT ");
        sb.append("INTO `");
        sb.append(context.getMainTable()).append("`(");
        sb.append(columns.toString()).append(") VALUES(");
        sb.append(values.toString()).append(");");

        return sb.toString();
    }

    @Override
    public ParamStatementSetter getParams() {
        return context.getParamSetter();
    }

    public void build(Object model) throws Exception {
        buildFlag = true;

        SqlContextManager contextManager = SqlContextManager.newInstance(context);
        for (FieldObject fieldObject : context.getFieldList()) {
            contextManager.setValue(fieldObject, model);
        }
    }

}
